package com.xiaofengstu.mcams.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaofengstu.mcams.dto.RoleDTO;
import com.xiaofengstu.mcams.web.entity.TMenu;
import com.xiaofengstu.mcams.web.entity.TRole;
import com.xiaofengstu.mcams.web.mapper.TRoleMapper;
import com.xiaofengstu.mcams.web.service.TMenuService;
import com.xiaofengstu.mcams.web.service.TRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-07
 */
@Service
@RequiredArgsConstructor
public class TRoleServiceImpl extends ServiceImpl<TRoleMapper, TRole> implements TRoleService {

  private final TRoleMapper roleMapper;

  private final TMenuService menuService;

  @Override
  public List<TRole> getRoleListContainMenu() {
    List<TRole> roleList = roleMapper.selectList(new QueryWrapper<>());
    for (TRole role : roleList) {
      String[] rights = role.getRoleAuth().split(",");
      List<TMenu> menuList = menuService.getMenuList(rights);
      role.setChild(menuList);
    }
    return roleList;
  }

  @Override
  public List<String> getAuthId(Integer roleId) {
    TRole role = roleMapper.selectById(roleId);
    List<String> list = new ArrayList<>();
    String[] split = role.getRoleAuth().split(",");
    for (String s : split) {
      if (!s.startsWith("1")){
        list.add(s);
      }
    }
    return list;
  }

  @Override
  public Integer updateRights(RoleDTO roleDTO) {
    TRole role = roleMapper.selectById(roleDTO.getRoleId());

    Map<String, Integer> map = new HashMap<>();
    StringBuilder sb = new StringBuilder();

    for (String s : roleDTO.getAuthIds()) {
      String menuPrefix = s.substring(0, 1);
      if (!map.containsKey(menuPrefix)) {
        TMenu menu = menuService.getById(s);
        map.put(menuPrefix, menu.getMenuPid());
        sb.append(menu.getMenuPid()).append(",");
      }
      sb.append(s).append(",");
    }

    role.setRoleAuth(sb.toString());

    return roleMapper.updateById(role);
  }

}
